package com.wjk.kylin.modules.system.role.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wjk.kylin.modules.system.role.entity.RoleDept;
import com.wjk.kylin.modules.system.role.mapper.RoleDeptMapper;
import com.wjk.kylin.modules.system.role.service.IRoleDeptService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 * 角色和部门关联表 服务实现类
 * </p>
 */
@Service
@Transactional(readOnly=true)
public class RoleDeptServiceImpl extends ServiceImpl<RoleDeptMapper, RoleDept> implements IRoleDeptService {


    @Override
    @Transactional(readOnly=false)
    public void deleteByRoleIds(List<String> roleIds) {
        QueryWrapper<RoleDept> wrapper = new QueryWrapper<>();
        wrapper.in("role_id", roleIds);

        super.remove(wrapper);
    }

    @Override
    @Transactional(readOnly=false)
    public void deleteByDeptIds(List<String> deptIds) {
        QueryWrapper<RoleDept> wrapper = new QueryWrapper<>();
        wrapper.in("dept_id", deptIds);

        super.remove(wrapper);
    }

    @Override
    public List<String> findDeptListByRoleId(String roleId) {
        QueryWrapper<RoleDept> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id", roleId);

        List<RoleDept> roleDeptList = super.list(wrapper);

        return roleDeptList.stream().map(RoleDept::getDeptId).distinct().collect(Collectors.toList());
    }

    @Override
    @Transactional(readOnly=false)
    public void save(String roleId, List<String> deptIds) {
        List<RoleDept> roleDeptList = new ArrayList<>();
        deptIds.forEach(deptId->{
            RoleDept roleDept = new RoleDept();

            roleDept.setDeptId(deptId);
            roleDept.setRoleId(roleId);

            roleDeptList.add(roleDept);
        });

        super.saveBatch(roleDeptList);
    }
}
